package com.ljyh.forum.controller;

import com.ljyh.forum.entity.Category;
import com.ljyh.forum.service.CategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 分类控制器
 */
@RestController
@RequestMapping("/categories")
@Tag(name = "分类接口", description = "帖子分类相关接口")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping
    @Operation(summary = "获取分类列表")
    public ApiResponse<List<Category>> getCategories() {
        List<Category> categories = categoryService.getAllCategories();
        return ApiResponse.success("查询成功", categories);
    }

    @PostMapping
    @Operation(summary = "添加分类（管理员）")
    public ApiResponse<Void> addCategory(@RequestBody CategoryRequest request) {
        boolean success = categoryService.addCategory(request.getName());
        if (success) {
            return ApiResponse.success("添加成功", null);
        } else {
            return ApiResponse.error(400, "分类名称已存在");
        }
    }

    @PutMapping("/{id}")
    @Operation(summary = "修改分类（管理员）")
    public ApiResponse<Void> updateCategory(@PathVariable Integer id, @RequestBody CategoryRequest request) {
        boolean success = categoryService.updateCategory(id, request.getName());
        if (success) {
            return ApiResponse.success("修改成功", null);
        } else {
            return ApiResponse.error(400, "修改失败，分类名称可能已存在");
        }
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除分类（管理员）")
    public ApiResponse<Void> deleteCategory(@PathVariable Integer id) {
        boolean success = categoryService.deleteCategory(id);
        if (success) {
            return ApiResponse.success("删除成功", null);
        } else {
            return ApiResponse.error(400, "删除失败，分类可能不存在或包含帖子");
        }
    }

    /**
     * 分类请求体
     */
    public static class CategoryRequest {
        private String name;

        // getters and setters
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
    }

    /**
     * 统一API响应格式
     */
    public static class ApiResponse<T> {
        private int code;
        private String msg;
        private T data;

        public ApiResponse(int code, String msg, T data) {
            this.code = code;
            this.msg = msg;
            this.data = data;
        }

        public static <T> ApiResponse<T> success(String msg, T data) {
            return new ApiResponse<>(200, msg, data);
        }

        public static <T> ApiResponse<T> error(int code, String msg) {
            return new ApiResponse<>(code, msg, null);
        }

        // getters
        public int getCode() { return code; }
        public String getMsg() { return msg; }
        public T getData() { return data; }
    }
}
